package app.conf;

import cn.hutool.core.lang.Console;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.annotation.PostConstruct;
import java.sql.*;

@Configuration
@PropertySource("classpath:application.yml")
public class StartConfiguration {
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.name}")
    private String name; // 数据库名
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    @Value("${spring.datasource.driver-class-name}")
    private String className;

    // 系统启动时
    @PostConstruct
    public void startConfiguration() {
        // 创建数据库
        Connection con = null;
        Statement cState = null;
        try {
            Class.forName(className);
            con = DriverManager.getConnection(url, username, password);
            String cSQL = "CREATE DATABASE " + name;
            cState = con.createStatement();
            boolean execute = cState.execute(cSQL);
            if (execute){
                Console.log("数据库创建成功");
                String cTable = "";
            }else{
                Console.log("创建数据库失败");
            }
        } catch (ClassNotFoundException ignored) {
            Console.error("找不到驱动");
        } catch (SQLException e) {
            Console.log("已存在数据库");
        } finally {
            try {
                // 关闭
                assert cState != null;
                cState.close();
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
